<template>
	<view class="address-list-container bottom-index">
		<!-- #ifdef MP-WEIXIN -->
		<qmy-custom-navbar :title="fromPage === 'order' ? '选择收货地址' : '我的地址'"></qmy-custom-navbar>
		<!-- #endif -->
		<!-- 加载中蒙版 -->
		<qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
		<!-- 内容区域 -->
		<view class="content" :style="{paddingTop:menuObject.top + menuObject.height +20 + 'px'}">
			<!-- 添加顶部提示横幅，仅在选择模式下显示 -->
			<view class="select-tip" v-if="['order','orderDetail'].includes(fromPage)">
				<text class="iconfont ic-tishi fs-32" style="color: #67c23a; margin-right: 10rpx;"></text>
				<text class="tip-text">点击选择收货地址</text>
			</view>

			<!-- 空地址状态 -->
			<view class="empty-state" v-if="addressList.length === 0">
				<image class="empty-image"
					src="https://gd-hbimg.huaban.com/1278ab9fe317810d1b61ad25d7a6c22cc2f9651983a9-kKpuhr_fw1200webp"
					mode="aspectFit"></image>
				<text class="empty-text">暂无收货地址，赶快添加吧</text>
			</view>

			<!-- 地址列表 -->
			<view class="address-list" v-else>
				<view class="address-item" v-for="(item, index) in addressList" :key="index">
					<view class="item-main" @click="selectAddress(item)">
						<view class="user-info">
							<text class="name">{{item.name}}</text>
							<text class="mobile">{{item.mobile}}</text>
							<view class="tag-box">
								<text class="default-tag" v-if="item.is_default">默认</text>
								<text class="alias-tag" v-if="item.alias">{{item.alias}}</text>
							</view>
						</view>
						<view class="address-detail">
							<text class="address-text">{{getFormattedAddress(item)}}</text>
						</view>
					</view>

					<!-- 单选按钮和操作按钮行 -->
					<view class="item-action-row">
						<!-- 设为默认单选按钮 -->
						<view class="default-selector" @click.stop="setAsDefault(item)">
							<view class="radio-btn" :class="{'radio-selected': item.is_default}">
								<view class="radio-inner" v-if="item.is_default"></view>
							</view>
							<text class="default-text">{{item.is_default?'默认地址':'设为默认地址'}}</text>
						</view>

						<!-- 操作按钮组 -->
						<view class="action-buttons">
							<view class="action-btn " @click="toNav(`/qmy_user/user/address/edit?id=${item._id}`)">
								<text class="btn-label">编辑</text>
							</view>
							<view class="action-btn " @click.stop="copyAddress(item)">
								<text class="btn-label">复制</text>
							</view>
							<view class="action-btn " @click.stop="confirmDelete(item)">
								<text class="btn-label">删除</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部定位发布按钮 -->
		<view class="w-100 fixed-bottom bac-col-00b" @click="toNav('/qmy_user/user/address/add')">
			<view class="w-100 bg-col-00b text-ali-c">
				<view class="fs-30 col-f fw-600">新增收货地址</view>
			</view>
		</view>

		<!-- 删除确认弹窗 -->
		<uni-popup ref="deletePopup" type="dialog">
			<uni-popup-dialog type="warning" title="删除确认" content="确定要删除这个收货地址吗？" :before-close="true"
				@confirm="confirmDeleteAction" @close="cancelDelete">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif
				addressList: [],
				fromPage: '', // 来源页面，用于判断是否需要选择地址并返回
				currentDeleteAddress: null, // 当前待删除的地址
				dataLoaded: false // 数据是否加载完成
			}
		},
		onLoad(options) {
			// 获取地址列表
			this.getAddressList();

			// 获取来源页面参数
			if (options && options.from) {
				this.fromPage = options.from;
			}
		},
		methods: {
			// 获取地址列表
			getAddressList() {
				this.$Route('get-private-data', !this.dataLoaded).getUserAddressList().then(res => {
					this.addressList = res.data;
					this.dataLoaded = true;
				}).catch(err => {
					this.dataLoaded = true;
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				});
			},
			// 获取格式化的地址
			getFormattedAddress(item) {
				if (item.formatted_address) {
					return item.formatted_address + item.address;
				} else {
					return `${item.province}${item.city}${item.district}${item.address}`;
				}
			},

			// 选择地址后返回上一级页面
			selectAddress(item) {
				if (['order', 'orderDetail'].includes(this.fromPage)) {
					// 如果是从订单页面进入，选择后返回
					const eventChannel = this.getOpenerEventChannel();
					eventChannel.emit('refreshData', item);
					uni.navigateBack();
				} else {
					// 非订单页面可以做其他处理，比如编辑
					this.toNav(`/qmy_user/user/address/edit?id=${item._id}`);
				}
			},

			// 确认是否删除地址
			confirmDelete(item) {
				this.currentDeleteAddress = item;
				this.$refs.deletePopup.open();
			},

			// 取消删除
			cancelDelete() {
				this.currentDeleteAddress = null;
				this.$refs.deletePopup.close();
			},

			// 新增/编辑地址
			toNav(path) {
				uni.navigateTo({
					url: path,
					events: {
						refreshData: () => {
							this.getAddressList();
						}
					}
				});
			},

			// 确认删除操作
			confirmDeleteAction() {
				if (!this.currentDeleteAddress) return;

				// 实际项目中应该调用接口删除
				this.$Route('update-private-data').deleteAddress(this.currentDeleteAddress._id).then(res => {
					this.getAddressList();
				}).catch(err => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				});

				this.currentDeleteAddress = null;
				this.$refs.deletePopup.close();
			},

			// 设置为默认地址
			setAsDefault(item) {
				if (item.is_default) return;
				// 更新默认地址
				this.$Route('update-private-data').editAddress(item._id, 'is_default').then(res => {
					// 处理响应
					this.getAddressList();
				}).catch(err => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				});
			},

			// 复制地址
			copyAddress(item) {
				const formattedAddress = this.getFormattedAddress(item);
				// #ifdef H5
				const textarea = document.createElement('textarea');
				textarea.value = `${item.name}, ${item.mobile}, ${formattedAddress}`;
				document.body.appendChild(textarea);
				textarea.select();
				document.execCommand('copy');
				document.body.removeChild(textarea);
				this.$Toast('地址已复制');
				// #endif

				// #ifdef APP-PLUS || MP-WEIXIN
				uni.setClipboardData({
					data: `${item.name}, ${item.mobile}, ${formattedAddress}`,
					success: () => {
						this.$Toast('地址已复制');
					},
					fail: (err) => {
						console.error('复制失败:', err);
						this.$Toast('复制失败,未获取剪切板权限');
					}
				});
				// #endif
			},
		}
	}
</script>

<style lang="scss" scoped>
	.address-list-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		position: relative;
	}

	.content {
		padding: 20rpx;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;

		.empty-image {
			width: 250rpx;
			height: 250rpx;
			margin-bottom: 30rpx;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	/* 顶部选择提示 */
	.select-tip {
		background-color: #f0f9eb;
		padding: 20rpx 30rpx;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		display: flex;
		align-items: center;

		.tip-text {
			color: #67c23a;
			font-size: 26rpx;
		}
	}

	/* 地址列表 */
	.address-list {
		.address-item {
			display: flex;
			flex-direction: column;
			background-color: #ffffff;
			padding: 24rpx 30rpx;
			margin-bottom: 20rpx;
			border-radius: 30rpx;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
			position: relative;
			overflow: hidden;

			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 0;
				width: 12rpx;
				height: 100%;
				background-color: #14cc60;
				border-radius: 0 3rpx 3rpx 0;
			}

			.item-main {
				flex: 1;

				.user-info {
					display: flex;
					align-items: center;
					margin-bottom: 16rpx;
					flex-wrap: wrap;

					.name {
						font-size: 30rpx;
						color: #333;
						font-weight: 600;
						margin-right: 20rpx;
					}

					.mobile {
						font-size: 28rpx;
						color: #666;
						font-weight: 600;
						margin-right: 20rpx;
					}

					.tag-box {
						display: flex;

						.default-tag,
						.alias-tag {
							font-size: 20rpx;
							padding: 2rpx 10rpx;
							border-radius: 6rpx;
							margin-right: 10rpx;
						}

						.default-tag {
							background-color: #14cc60;
							color: #ffffff;
						}

						.alias-tag {
							background-color: #f0f9ff;
							color: #0091ff;
						}
					}
				}

				.address-detail {
					.address-text {
						font-size: 28rpx;
						color: #333;
						line-height: 1.4;
					}
				}
			}

			/* 按钮操作行 - 新增 */
			.item-action-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 24rpx;
				padding-top: 24rpx;
				border-top: 1rpx solid #eee;

				/* 默认单选按钮 */
				.default-selector {
					display: flex;
					align-items: center;

					.radio-btn {
						width: 36rpx;
						height: 36rpx;
						border-radius: 50%;
						border: 2rpx solid #ccc;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 10rpx;

						&.radio-selected {
							border-color: #14cc60;
						}

						.radio-inner {
							width: 20rpx;
							height: 20rpx;
							border-radius: 50%;
							background-color: #14cc60;
						}
					}

					.default-text {
						font-size: 24rpx;
						color: #666;
					}
				}

				/* 操作按钮组 */
				.action-buttons {
					display: flex;

					.action-btn {
						display: flex;
						align-items: center;
						justify-content: center;
						margin-left: 30rpx;
						background-color: #f7f7f7;
						border-radius: 6rpx;
						width: 80rpx;
						height: 45rpx;
						line-height: 45rpx;
						text-align: center;
						color: #333;

						.iconfont {
							margin-right: 8rpx;
						}

						.btn-label {
							font-size: 24rpx;
						}
					}
				}
			}

			/* 可选择的地址项样式 */
			&.selectable {
				position: relative;
				border: 1rpx solid transparent;
				transition: all 0.2s ease;

				&:active {
					background-color: #f8f8f8;
					border-color: #14cc60;
					transform: translateY(2rpx);
				}
			}

			&:active {
				transform: scale(0.98);
				transition: transform 0.2s;
			}
		}
	}

	/* 添加选择图标样式 */
	.select-icon {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #999;
		font-size: 36rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		padding-top: 30rpx;
		padding-bottom: 30rpx !important;
		padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)) !important;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom)) !important;
		z-index: 9999;
		transition: background-color 0.2s ease;
	}

	.fixed-bottom:active {
		background-color: #11b051 !important;
		/* 点击时背景颜色变化 */
	}
</style>